package com.jumi.microservice.aspectj;

import cn.hutool.core.util.StrUtil;
import com.jm.member.common.core.utils.DelFlag;
import com.jm.member.common.core.utils.ServletUtils;
import com.jm.member.common.jwt.constant.JwtAdminInfo;
import com.jumi.microservice.datasource.annotation.AdminChangeUserLog;
import com.jumi.microservice.entity.JmAdminChangeUserLog;
import com.jumi.microservice.enums.CommonEnum;
import com.jumi.microservice.service.IJmAdminChangeUserLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
public class AdminChangeUserLogAspect {


    private static ThreadLocal<String> BACKUP =new ThreadLocal<>();
    private static ThreadLocal<Integer> UID =new ThreadLocal<>();

    public static void setBack(String msg,Integer uid){
        BACKUP.set(msg);
        UID.set(uid);
    }
    public static String getBack(){
        String s = BACKUP.get();
        BACKUP.remove();
        return s;
    }

    public static Integer getUID(){
        Integer uid = UID.get();
        UID.remove();
        return uid;
    }

    @Autowired
    IJmAdminChangeUserLogService userLogService;


    @Pointcut("@annotation(com.jumi.microservice.datasource.annotation.AdminChangeUserLog)")
    public void dsPointCut()
    {

    }

    @AfterReturning("dsPointCut()")
    public void after(JoinPoint point)
    {
        Long adminId = ServletUtils.getLoginId();
        String adminName = ServletUtils.getLoginName();
        if(StrUtil.isEmpty(adminName)){
            adminId=Long.valueOf(ServletUtils.getIntHeader(JwtAdminInfo.apiUserId));
            adminName=ServletUtils.getStrHeader(JwtAdminInfo.apiTrueName);
        }

        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        AdminChangeUserLog annotation = method.getDeclaredAnnotation(AdminChangeUserLog.class);
        if(annotation!=null){
            LocalDateTime now = LocalDateTime.now();
            String value = annotation.value();//操作类型
            JmAdminChangeUserLog log=new JmAdminChangeUserLog();
            log.setUid(getUID());
            log.setType(value);
            log.setAdminId(adminId);
            log.setAdminName(adminName);
            log.setBackup(getBack());
            log.setUpdateTime(now);
            log.setCreateTime(now);
            log.setDel(DelFlag.normal);
            userLogService.save(log);
        }
    }
}
